using Magiq.Update;

namespace Magiq.Databases.Update
{
    public class DatabaseUpdateStrategy<T> : IUpdateStrategy,
                                             IDatabaseBasedExecution where T : class
    {
        private readonly IUpdate<T> update;

        public DatabaseUpdateStrategy(IOrmAdapter ormAdapter, IUpdate<T> update)
        {
            OrmAdapter = ormAdapter;
            this.update = update;
        }

        #region IDatabaseBasedExecution Members

        public IOrmAdapter OrmAdapter { get; private set; }

        #endregion

        #region IUpdateStrategy Members

        public int Execute()
        {

            var updates = OrmAdapter.BuildDatabaseUpdates(update);
            var result = 0;
            foreach (var databaseUpdate in updates)
            {
                var where = databaseUpdate.Source;
                var builder = new UpdateCommandBuilder(databaseUpdate.OrmAdapter, where,
                                                       databaseUpdate.ColumnAssignments);
                var command = builder.GetCommand();
                
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }

        #endregion
    }
}